package labox.innovation.gameserver.model.actor.instance;

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import labox.innovation.config.Config;
import labox.innovation.gameserver.datatables.TeleportCostsConfig;
import labox.innovation.gameserver.model.FuzeWorld;
import labox.innovation.gameserver.model.Scene;
import labox.innovation.gameserver.network.SystemMessageId;
import labox.innovation.gameserver.network.serverpackets.ActionFailed;
import labox.innovation.gameserver.network.serverpackets.NpcHtmlMessage;
import labox.innovation.gameserver.network.serverpackets.SystemMessage;
import labox.innovation.gameserver.templates.chars.NpcTemplate;
import labox.innovation.gameserver.templates.item.FuzeEconomicManager.OPSTATE;

/**
 * 传送师对象
 * 
 */
public final class FuzeTeleporterInstance extends FuzeNpcInstance {

	private static final Logger _log = LoggerFactory.getLogger(FuzeTeleporterInstance.class.getName());

	/**
	 * 所有的传送情况都失败
	 */
	private static final int COND_ALL_FALSE = 0;

	/**
	 * 拥有这个传送师
	 */
	private static final int COND_OWNER = 2;

	/**
	 * 通常的传送情况
	 */
	private static final int COND_REGULAR = 3;

	/**
	 * @param template
	 */
	public FuzeTeleporterInstance(long objectId, NpcTemplate template) {
		super(objectId, template);
	}

	@Override
	public void onBypassFeedback(FuzePcInstance player, String command) {
		int condition = validateCondition(player);

		StringTokenizer st = new StringTokenizer(command, " ");
		String actualCommand = st.nextToken(); // Get actual command

		if (actualCommand.equalsIgnoreCase("goto")) {
			if (st.countTokens() <= 0)
				return;

			String whereTo = st.nextToken().replace("$", "").replace("#", "");
			String priceStr = TeleportCostsConfig.getInstance().getPriceByPath(String.valueOf(player.getScene().get_id() + "~" + whereTo));

			if (priceStr != null && !"".equals(priceStr)) {
				int price = Integer.valueOf(priceStr);
				if (condition == COND_REGULAR) {
					doTeleport(player, Integer.valueOf(whereTo), price);
					return;
				}
			} else {
				player.sendPacket(new SystemMessage(SystemMessageId.TELEPORT_BE_BANED));
				return;
			}

		} else if (command.startsWith("Chat")) {
			int val = 0;
			try {
				val = Integer.parseInt(command.substring(5));
			} catch (IndexOutOfBoundsException ioobe) {
			} catch (NumberFormatException nfe) {
			}

			showChatWindow(player, val);
		}

		super.onBypassFeedback(player, command);
	}

	@Override
	public void showChatWindow(FuzePcInstance player) {
		String filename = "data/html/teleporter/castleteleporter-no.htm";

		int condition = validateCondition(player);
		if (condition == COND_REGULAR) {
			super.showChatWindow(player);
			return;
		}

		NpcHtmlMessage html = new NpcHtmlMessage(getObjectId());
		html.setFile(filename);
		html.replace("%objectId%", String.valueOf(getObjectId()));
		//		html.replace("%scene_name%", TeleportLocationTable.getInstance().getTemplate());
		html.replace("%npcname%", getName());
		player.sendPacket(html);

	}

	@Override
	public void showChatWindow(FuzePcInstance player, int val) {
		String sceneID;
		String currentSceneID;
		String sceneName;
		String path;
		Scene targetScene;
		int npcId = getTemplate()._id;
		String filename;
		filename = (getHtmlPath(npcId, val));
		NpcHtmlMessage html = new NpcHtmlMessage(getObjectId());
		html.setFile(filename);
		String content = html.getHtml();

		if (Config.LIST_PET_RENT_NPC.contains(npcId))
			html.replace("_Quest", "_RentPet\">Rent Pet</a><br><a action=\"bypass -h npc_%objectId%_Quest");

		html.replace("%objectId%", String.valueOf(getObjectId()));
		currentSceneID = String.valueOf(player.getScene().get_id());
		String ps = "\\$\\d+\\#";
		Pattern p = Pattern.compile(ps);
		Matcher m = p.matcher(content);

		while (m.find()) {
			sceneID = content.substring(m.start() + 1, m.end() - 1);
			targetScene = FuzeWorld.getInstance().getScene(Integer.valueOf(sceneID));
			sceneName = targetScene.getName();
			html.replace("%scene_name_" + sceneID + "%", sceneName);
			path = currentSceneID + "~" + sceneID;
			if (TeleportCostsConfig.getInstance().getPriceByPath(path) != null && !"".equals(TeleportCostsConfig.getInstance().getPriceByPath(path))) {
				html.replace("%teleprt_cost_" + sceneID + "%", TeleportCostsConfig.getInstance().getPriceByPath(path));
			} else {
				String replaceStr = "需%teleprt_cost_" + sceneID + "%银文";
				html.replace(replaceStr, "不能到达！");
			}

		}
		player.sendPacket(html);

		player.sendPacket(ActionFailed.STATIC_PACKET);
	}

	/**
	 * 
	 * @param player
	 * @param val
	 * @param price
	 */
	private void doTeleport(FuzePcInstance player, int val, int price) {
		Scene list = FuzeWorld.getInstance().getScene(val);
		if (list != null) {
//			if (player.getKarma() > 0) { //karma
//				player.sendMessage("Go away, you're not welcome here.");
//				return;
//			}
			if (player.isDead())
				return;
			
			if (!player.getInventory().hasEnoughSilverMoney(OPSTATE.TELEPORT.getValue(), player, price)) {
				player.sendPacket(new SystemMessage(SystemMessageId.YOU_NOT_ENOUGH_ADENA));
				return;
			}
			
			

			if (player.reduceMoneySilver(OPSTATE.TELEPORT.getValue(), price, this, true)) {
				if (_log.isDebugEnabled())
					_log.debug("Teleporting player " + player.getName() + " to new location: " + list.getTele2X() + ":" + list.getTele2Y(), Config.SERVER_ID, "NPC传送");

				player.teleToLocation(list.get_id(), list.getTele2X(), list.getTele2Y());
			}
		} else
			_log.warn("No teleport destination with id:" + val, Config.SERVER_ID, "NPC传送");

		player.sendPacket(ActionFailed.STATIC_PACKET);
	}

	private int validateCondition(FuzePcInstance player) {
		return COND_REGULAR; // Regular access
	}
}
